<template>
    <div class="warp" style="height:100%;">
        <navbar :title="$t('circle_kg_19')" v-if="sourceType === 'ARTICLE'"></navbar>
        <navbar :title="$t('circle_kg_19')" v-if="sourceType !== 'ARTICLE'"></navbar>
        <div class="content-noBottom" style="background: #fff">
            <van-pull-refresh v-model="isRefresh" @refresh="onPulldownTop" loading-text="loading" pulling-text="" loosing-text="" style="height: 100%;">
                <van-list
                    v-model="isLoading"
                    :finished="finished"
                    :finished-text="(finished&&total>0) ? $t('no_more') : ''"
                    loding-text="loading"
                    @load="getKgCommentByKbiId"
                    style="padding-bottom: 56px;">
                    <div class="info-body">
                        <input id="resourcesPath" style="position: absolute;left: -1px;top: -1px;z-index: -10">
                        <div class="view-body" style="box-sizing: border-box;border-bottom: 1px dashed #cccccc;" :style="{'padding-top': sourceType === 'ARTICLE' ? '' : '211px'}">
                            <div class="white-bg">
                                <div class="play-box" v-if="sourceType !== 'ARTICLE'">
                                    <div class="bg-banner"></div>
                                    <span class="btn-title" @click="openDoc">{{ $t("knowledge_open_doc") }}</span><!--打开文件-->
                                </div>
                                <div class="paddingLR15">
                                    <p class="font-size20" style="font-weight: bold;padding: 20px 0 15px;">{{ kgData.kbiTitle }}</p>
                                    <p class="font-size11 color999" style="padding-bottom: 15px;">
                                        <span>{{ kgData.kbiPublishDatetime }}</span>
                                        <em class="point"></em>
                                        <span>{{ kgData.usrDisplayBil }}</span>
                                        <a style="float: right;color: #999" v-if="kgData && kgData.kbiDownload === '1' && kgData.attachments.length > 0" :href="appUrl + kgData.attachments[0].url" download>{{ $t('circle_kg_62') }}</a>
                                    </p>

                                    <p class="font-size20 color999 btn-bars" style="padding-bottom: 15px;">
                                        <span @click="likeHandle(kgData.kbiId, kgData.valuation, -1)" :class="{'handle-ok': kgData.valuation}"><van-icon name="good-job-o"/><span>{{ kgData.valuationCount }}</span></span>
                                        <span @click="favoritesHandle(kgData.kbiId, kgData.favorites)" :class="{'handle-ok': kgData.favorites}"><van-icon name="star-o"/><span>{{ kgData.favoritesCount }}</span></span>
                                        <span><van-icon name="balance-o" @click="optionPlayTour"/><span>{{ $t('circle_kg_63') }}</span></span>
                                        <span @click="isShowSelectUser = true"><van-icon name="share-o"/><span>{{ $t('circle_kg_64') }}</span></span>
                                    </p>
                                    <div style="padding-bottom: 10px;color: #999;text-align: right" v-if="kgData.kbiDocumentSourceType === 1" @click="copyResourcePath(kgData.kbiDocumentSourceUrl)">{{$t('copy_original_address')}}</div>
                                </div>
                            </div>
                        </div>
                        <div style="padding: 10px 15px;border-bottom: 1px dashed #cccccc" v-if="sourceType === 'ARTICLE'">
                            <div v-html="$xss(htmlFilter(kgData.kbiContent))"></div>
                            <div style="text-align: right" v-if="kgData.attachments && kgData.attachments.length > 0">
                                <van-button type="info" size="mini" @click="openDoc">{{ $t('knowledge_open_doc') }}</van-button>
                            </div>
                            <div style="padding: 10px 0;color: #999" v-if="kgData.kbiDocumentSourceType === 1" @click="copyResourcePath(kgData.kbiDocumentSourceUrl)">{{$t('copy_original_address')}}</div>

                        </div>
                        <div class="info-list">
                            <div style="padding: 10px 0">{{ $t('circle_kg_65', {'value':  kgData.commentCount}) }}</div>
                            <div class="info-item" v-for="(item, index) in list" :key="item.cmtId">
                                <div class="info-img">
                                    <van-image round width="40px" height="40px" :src="appUrl + item.commentUserImage"/>
                                </div>
                                <div class="info-detail">
                                    <div class="info-top">
                                        <div class="info-name">{{ item.commentUser }}</div>
                                        <div class="info-date">{{ item.commentTime | formTime(item.serverTime)}}</div>
                                    </div>
                                    <div class="info-content" v-html="$xss(htmlFilter(item.content))"></div>
                                    <div class="info-bottom">
                                        <span>
                                            <span @click="likeHandle(item.cmtId, item.isLike, index)" :class="{'handle-ok': item.isLike}"><van-icon name="good-job-o"/><span>{{ item.likeCount }}</span></span>
                                            <span @click="commentTop(item.cmtId, null)"><van-icon name="comment-o"/><span>{{ item.countReply }}</span></span>
                                            <span v-if="item.childComment && item.childComment.length > 0" @click="showIng(item.cmtId)" style="font-size: 14px;color: #1F52CC">{{ $t('circle_kg_66') }}</span>
                                        </span>
                                        <span @click="deleteComment(item.cmtId)"><van-icon name="delete"/></span>
                                    </div>
                                    <div class="info-ing" v-show="item.childComment && item.childComment.length > 0 && showIngMap.has(item.cmtId)">
                                        <div class="ing-item" v-for="comment in item.childComment" :key="comment.cmtId">
                                            <div class="ing-top">
                                                <span>
                                                    <span>{{ comment.commentUser }}</span>
                                                    <span v-if="comment.replyUser">{{ $t('circle_kg_69') }} {{ comment.replyUser }}</span>
                                                    <span>：</span>
                                                </span>
                                                <span v-html="$xss(htmlFilter(comment.content))"></span>
                                            </div>
                                            <div class="ing-bottom">
                                                <span>{{ comment.commentTime | formTime(item.serverTime)}}</span>
                                                <span @click="commentTop(item.cmtId, comment.cmtId)">{{ $t('circle_kg_67') }}</span>
                                                <span @click="deleteComment(comment.cmtId)">{{ $t('circle_kg_5') }}</span>
                                            </div>
                                        </div>
                                        <div class="ing-shouqi" @click="closeIng(item.cmtId)">{{ $t('circle_kg_68') }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div v-if="!isLoading && total === 0" style="height:100%;">
                            <div class="box-table" style="width:100%;height:100%;">
                                <div class="box-table-cell" style="text-align: center;">
                                    <div class="no-data">
                                        <img src="../../../../static/images/no-data.png" alt=""/>
                                        <p class="color999">{{ $t("no_data") }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>
        <div class="comment-main" v-show="!isShowComment" @click="showComment(true)">{{ $t('circle278') }}</div>
        <comment ref="commentRef" @valChange="commentTextHandle" @changeUserList="changeUserList" :placeholder="placeholder">
            <div>
                <van-button size="mini" @click="closeComment">{{ $t('circle_kg_13') }}</van-button>
                <van-button type="info" size="mini" @click="saveComment">{{ $t('circle_kg_70') }}</van-button>
            </div>
        </comment>
        <common-loading :isLoading="isLoading"></common-loading>
<!--        <select-group-user :is-show.sync="isShowSelectUser" @changeIdList="selectUserHandle"></select-group-user>-->
        <new-select-user :is-show.sync="isShowSelectUser" @changeIdList="selectUserHandle"></new-select-user>
        <PlayTour ref="playTour" :data="playTour"  @playTourSuccessful="playTourSuccessful"></PlayTour>
    </div>
</template>

<script>
import { Toast, Image, Dialog, Icon, Button } from 'vant';
import Comment from '../../../repeatComponents/comment/Comment';
// import SelectGroupUser from '../../common/SelectGroupUser';
import PlayTour from '../../../repeatComponents/playTour/PlayTour';
import NewSelectUser from '../../common/NewSelectUser';
import {cwnEncrypt, cwnDecrypt} from '@/utils/tools';
export default {
    name: 'KnowledgeInfo',
    components: {
        NewSelectUser,
        Comment,
        PlayTour,
        vanIcon: Icon,
        vanImage: Image,
        vanButton: Button,
        vanDialog: Dialog
    },
    data() {
        return {
            total: 0,
            pageNo: 0,
            list: [],
            isLoading: false,
            moreShow: false,
            kbiId: this.$route.params.kbiId,
            kgData: {
                // kbiTitle: '',
                // kbiPublishDatetime: '',
                // usrDisplayBil: '',
                // kbiDownload: ''
            },
            isShowComment: false,
            comment: {
                content: '',
                commentId: 0,
                topCommentId: 0,
                // targetId: this.kbiId.toString(),
                type: 'KNOWLEDGE'
            },
            showIngMap: new Map(),
            placeholder: 'circle278',
            isShowSelectUser: false,
            playTour: {
                code: 'KNOWLEDGE',
                dataId: this.$route.params.kbiId,
                localIntegral: 0
            },
            sourceType: this.$route.params.type,
            finished: false,
            isRefresh: false
        };
    },
    methods: {
        ...{ cwnDecrypt },
        copyResourcePath(path) {
            let ele = document.getElementById('resourcesPath');
            ele.value = path;
            ele.select();
            document.execCommand('copy');
            Dialog.alert({
                width: '180px',
                confirmButtonText: this.$t('mall_10'),
                confirmButtonColor: '#00aeef',
                message: this.$t('copy_tips')
            });
        },
        selectUserHandle(userList) {
            if (userList.length > 0) {
                this.isLoading = true;
                let data = {
                    content: this.kgData.kbiTitle,
                    subject: this.kgData.kbiTitle,
                    recEntIds: userList,
                    mtpId: this.kbiId,
                    code: 'KNOWLEDGE'
                };
                this.$axios.post('/app/api/share/save', data).then(res => {
                    this.isLoading = false;
                    Toast({message: this.$t('circle_kg_72'), forbidClick: true});
                });
            }
        },
        closeComment() {
            this.$refs.commentRef.closeComment();
            this.isShowComment = false;
        },
        downDoc() {
            window.location.href = `${this.kgData.attachments[0].url}`;
        },
        openDoc() {
            if (!this.isLoading && this.kgData.attachments && this.kgData.attachments.length > 0) {
                this.$router.push({path: '/circle/knowledge/view', query: this.kgData});
            }
        },
        changeUserList(data) {
            this.comment.atUsers = data;
        },
        deleteComment(id) {
            if (!this.isLoading) {
                Dialog.confirm({
                    message: this.$t('circle_kg_6')
                }).then(() => {
                    this.isLoading = true;
                    this.$axios.delete(`/app/api/comment/${id}/COURSE`).then(res => {
                        Toast({message: this.$t('circle_kg_7'), forbidClick: true});
                        this.list = [];
                        this.onPulldownTop();
                    });
                });
            }
        },
        favoritesHandle(id, isfavorites) {
            if (!this.isLoading) {
                this.isLoading = true;
                let data = {
                    targetId: id,
                    module: 'KNOWLEDGE'
                };
                this.$axios({
                    method: isfavorites ? 'DELETE' : 'POST',
                    url: '/app/api/collect',
                    params: data
                }).then(res => {
                    this.kgData.favorites = !isfavorites;
                    this.kgData.favoritesCount += this.kgData.favorites ? 1 : -1;
                    this.isLoading = false;
                });
            }
        },
        likeHandle(id, isLike, index) {
            if (!this.isLoading) {
                this.isLoading = true;
                let data = {
                    targetId: id,
                    isLike: !isLike,
                    isComment: index !== -1,
                    typeEnum: 'KNOWLEDGE'
                };
                this.$axios.post('/app/api/valuation/like', data).then(res => {
                    if (index === -1) {
                        this.kgData.valuation = data.isLike;
                        this.kgData.valuationCount += data.isLike ? 1 : -1;
                    } else {
                        this.list[index].isLike = data.isLike;
                        this.list[index].likeCount += data.isLike ? 1 : -1;
                    }
                    this.isLoading = false;
                });
            }
        },
        showIng(id) {
            if (!this.showIngMap.has(id)) {
                this.showIngMap.set(id);
                this.$forceUpdate();
            }
        },
        // 开启打赏
        optionPlayTour() {
            this.$refs.playTour.openPlayTour();
        },
        //获取用户当前积分
        getUserIntegral() {
            this.$axios({
                url: '/app/credit/user'
            }).then(res => {
                this.playTour.localIntegral = res.data;
            });
        },
        //打赏成功
        playTourSuccessful() {
            Toast({message: this.$t('circle294'), forbidClick: true});
            this.getUserIntegral();
        },
        closeIng(id) {
            this.showIngMap.delete(id);
            this.$forceUpdate();
        },
        commentTop(topId, id) {
            this.comment.topCommentId = topId;
            if (id) {
                this.comment.commentId = id;
            } else {
                this.comment.commentId = topId;
            }
            this.showComment(false);
        },
        saveComment() {
            this.isLoading = true;
            this.$refs.commentRef.changeUserList();
            let data = Object.assign({}, this.comment);
            if (data.topCommentId === 0) {
                data.targetId = this.kbiId;
            }
            this.$axios.post('/app/api/comment', data).then(res => {
                this.$refs.commentRef.closeComment();
                this.comment = {
                    content: '',
                    commentId: 0,
                    topCommentId: 0,
                    type: 'KNOWLEDGE'
                };
                this.list = [];
                this.isShowComment = false;
                this.onPulldownTop();
                this.$refs.commentRef.clearComment();
            }).catch(res => {
                this.isLoading = true;
                this.$refs.commentRef.clearComment();
            });
        },
        commentTextHandle(txt) {
            this.comment.content = txt;
        },
        showComment(isKgComment) {
            if (isKgComment) {
                this.placeholder = 'circle278';
            } else {
                this.placeholder = 'circle_kg_71';
            }
            if (!this.isShowComment && !this.isLoading) {
                this.isShowComment = true;
                this.$refs.commentRef.openComment();
            }
        },
        /*下拉刷新*/
        onPulldownTop() {
            this.isRefresh = true;
            setTimeout(() => {
                this.finished = false;
                this.pageNo = 1;
                this.getKgCommentByKbiId('refresh');
                this.isRefresh = false;
            }, 900);
        },
        getKgDataByKbiId() {
            this.$axios.get(`/app/api/trainee/kb/item/detail/${this.kbiId}`).then((res) => {
                if (res.data) {
                    if (res.data.kbiContent) {
                        let content = res.data.kbiContent;
                        let reg = new RegExp('(?<=(src="))[^"]*?(?=")', 'ig');
                        let allSrc = content.match(reg);
                        if (allSrc && allSrc.length > 0) {
                            allSrc.forEach(item => {
                                if (item.indexOf('/') === 0) {
                                    content = content.replace(item, this.appUrl + item);
                                }
                            });
                            res.data.kbiContent = content;
                        }
                    }
                    this.kgData = res.data;
                }
            });
        },
        getKgCommentByKbiId(option) {
            this.$axios({
                method: 'post',
                url: '/app/api/comment/list',
                params: {
                    pageNo: this.pageNo
                },
                data: {
                    type: 'KNOWLEDGE',
                    targetId: this.cwnDecrypt(this.kbiId),
                    isTop: true
                }
            }).then(res => {
                if (res.data.results && res.data.results.length !== 0) {
                    if (option && option === 'refresh') {
                        this.list = res.data.results;
                    } else {
                        this.list = [...this.list, ...res.data.results];
                    }
                    this.kgData.commentCount = res.data.totalRecord;
                }
                this.total = res.data.totalRecord;
                this.isLoading = false;
                this.pageNo++;
                if (this.list.length >= this.total) {
                    this.finished = true;
                }
            });
        }
    },
    mounted() {
        // this.$refs.commentRef.openCommentNotKeyUp();
    },
    created() {
        // this.kbiId = this.$route.params.kbiId;
        this.isLoading = true;
        this.getKgDataByKbiId();
        this.onPulldownTop();
        this.getUserIntegral();
    }
};
</script>

<style scoped lang="less">
    .comment-main {
        position: fixed;
        bottom: 0;
        padding: 10px 15px;
        color: #999;
        background: #fff;
        border-top: 1px #CCCCCC solid;
        border-bottom: 1px #CCCCCC solid;
        width: 100%;
    }
    .info-body {
        height: 100%;
        background: #fff;
        .view-body{
            height: 100%;
            position: relative;
            .play-box {
                position: relative;
                width: 100%;
                height: 211px;
                margin-top: -211px;
                .btn-title {
                    padding: 8px 12px;
                    background: rgba(0,0,0,0.5);
                    border-radius: 8px;
                    color: #ffffff;
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%,-50%);
                    z-index: 0 !important;
                }
                .bg-banner {
                    width: 100%;
                    height: 100%;
                    background: url(../../knowledge/images/banner-doc.jpg) no-repeat center center;
                    background-size: auto 100%;
                    position: absolute;
                    /*z-index: 3;*/
                }
            }
            .btn-bars {
                display: flex;
                align-items: center;
                justify-content: space-between;
                &>span {
                    display: flex;
                    align-items: center;
                    &>span {
                        font-size: 14px;
                        margin-left: 2px;
                    }
                }
            }
        }
        .info-list {
            padding: 0 15px;
            .info-item {
                padding: 10px 0;
                display: flex;
                align-items: flex-start;
                border-bottom: 1px #CCCCCC solid;
                &:last-child {
                    border-bottom: none;
                }
                .info-img {
                    height: 40px;
                    width: 40px;
                    margin-right: 10px;
                }
                .info-detail {
                    flex-grow: 1;
                    .info-top {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        .info-date {
                            color: #999999;
                            font-size: 10px;
                        }
                    }
                    .info-content {
                        margin-top: 5px;
                    }
                    .info-bottom {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        margin-top: 5px;
                        &>span:not(:last-child) {
                            display: flex;
                            align-items: center;
                        }
                        &>span>span {
                            display: flex;
                            align-items: center;
                            font-size: 16px;
                            color: #999999;
                            margin-right: 30px;
                            &>span {
                                margin-left: 2px;
                                font-size: 14px;
                            }
                        }
                        &>span:last-child {
                            font-size: 16px;
                            color: #999999;
                            display: flex;
                            align-items: center;
                        }
                    }
                    .info-ing {
                        margin-top: 10px;
                        /*&>div:last-child(+1) {*/
                        /*    margin-bottom: 0;*/
                        /*}*/
                        .ing-item {
                            margin-bottom: 10px;
                            &:last-child{
                                margin-bottom: 0;
                            }
                            .ing-top {
                                &>span:first-child>span:last-child {
                                    margin-right: 2px;
                                }
                            }
                            .ing-bottom {
                                margin-top: 5px;
                                display: flex;
                                align-items: center;
                                font-size: 12px;
                                &>span:first-child {
                                    color: #999999;
                                }
                                &>span {
                                    margin-right: 20px;
                                    color: #1F52CC;
                                }
                                &>span:last-child {
                                    float: right;
                                }
                            }
                        }
                        .ing-shouqi {
                            color: #1F52CC;
                            text-align: right;
                            font-size: 12px;
                        }
                    }
                }
            }
        }
    }
    .handle-ok {
        color: #1F52CC !important;
    }
</style>
